/**
 * 网络请求优化工具
 */

// 请求队列管理
class RequestQueue {
  constructor() {
    this.queue = new Map();
    this.cache = new Map();
  }

  // 生成请求键
  generateKey(url, params) {
    return `${url}_${JSON.stringify(params || {})}`;
  }

  // 检查缓存
  getCache(key, maxAge = 5 * 60 * 1000) {
    const cached = this.cache.get(key);
    if (cached && (Date.now() - cached.timestamp) < maxAge) {
      return cached.data;
    }
    return null;
  }

  // 设置缓存
  setCache(key, data) {
    this.cache.set(key, {
      data,
      timestamp: Date.now()
    });
  }

  // 清除缓存
  clearCache(pattern = null) {
    if (pattern) {
      for (const key of this.cache.keys()) {
        if (key.includes(pattern)) {
          this.cache.delete(key);
        }
      }
    } else {
      this.cache.clear();
    }
  }

  // 带重试的请求
  async requestWithRetry(requestFn, retries = 3, delay = 1000) {
    for (let i = 0; i <= retries; i++) {
      try {
        return await requestFn();
      } catch (error) {
        if (i === retries) throw error;
        await this.delay(delay * Math.pow(2, i));
      }
    }
  }

  // 带超时的请求
  async requestWithTimeout(requestFn, timeout = 10000) {
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), timeout);
    });
    return Promise.race([requestFn(), timeoutPromise]);
  }

  // 请求去重
  async deduplicateRequest(key, requestFn) {
    if (this.queue.has(key)) {
      return this.queue.get(key);
    }
    const promise = requestFn();
    this.queue.set(key, promise);
    try {
      return await promise;
    } finally {
      this.queue.delete(key);
    }
  }

  // 智能缓存策略
  async smartRequest(requestFn, options = {}) {
    const {
      cacheKey = null,
      cacheAge = 5 * 60 * 1000,
      useCache = true,
      retries = 2,
      timeout = 10000,
      deduplicate = true
    } = options;

    const key = cacheKey || this.generateKey(requestFn.name || 'request', options);

    // 检查缓存
    if (useCache) {
      const cached = this.getCache(key, cacheAge);
      if (cached) return cached;
    }

    // 执行请求
    const request = () => this.requestWithTimeout(requestFn, timeout);
    const result = deduplicate 
      ? await this.deduplicateRequest(key, () => this.requestWithRetry(request, retries))
      : await this.requestWithRetry(request, retries);

    // 缓存结果
    if (useCache && result) {
      this.setCache(key, result);
    }

    return result;
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// 创建全局实例
const requestQueue = new RequestQueue();

// 导出工具函数
export const networkOptimizer = {
  // 智能请求
  async smartRequest(requestFn, options = {}) {
    return requestQueue.smartRequest(requestFn, options);
  },

  // 清除缓存
  clearCache(pattern = null) {
    requestQueue.clearCache(pattern);
  },

  // 创建请求配置
  createRequestConfig(options = {}) {
    return {
      cacheAge: 5 * 60 * 1000,
      useCache: true,
      retries: 2,
      timeout: 10000,
      deduplicate: true,
      ...options
    };
  }
}; 